//
//  CSToolBox.m
//  CSUIKit
//
//  Created by 网新中研 on 2017/5/4.
//  Copyright © 2017年 SoulFireWang. All rights reserved.
//

#import "CSToolBox.h"
#import <CSUIKit/CSUIKit.h>

@interface CSToolBox()

@property (nonatomic, assign) CGPoint startPont;

@property (nonatomic, strong) NSArray *buttons;

@end

@implementation CSToolBox

#define ITEM_WIDTH 120.0
#define ITEM_HEIGHT 40.0

-(instancetype)init{
    if (self = [super init]) {
        self.layer.cornerRadius = 5;
        self.layer.shadowOffset = CGSizeMake(0, 1);
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOpacity = 0.4;
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

-(id)initWithButtons:(NSArray *)buttons{
    if (self = [self init]) {
        _buttons = buttons;
        
        [self layoutView];
    }
    return self;
}

-(void)layoutView{
    for (int i = 0; i < _buttons.count; i++) {
        UIButton *button = (UIButton *)[_buttons objectAtIndex:i];
        button.frame = CGRectMake(0, i * (ITEM_HEIGHT - 1), ITEM_WIDTH, ITEM_HEIGHT);
//        button.userInteractionEnabled = NO;
        button.layer.borderColor = [UIColor colorFromHexCode:@"BBBBBB"].CGColor;
//        button.layer.borderWidth = 1;
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16.0];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:button];
    }
    
    CGFloat needHeight = (ITEM_HEIGHT - 1) * _buttons.count;
    
    self.frame = CGRectMake(kWindowW - ITEM_WIDTH - 10, (kWindowH - needHeight - 10), ITEM_WIDTH, needHeight);
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint point = [[touches anyObject] locationInView:self];
    _startPont = point;
    
    [[self superview] bringSubviewToFront:self];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint point = [[touches anyObject] locationInView:self];
    float dx = point.x - _startPont.x;
    float dy = point.y - _startPont.y;
    
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    
    float halfx = CGRectGetMidX(self.bounds);
    
    //x坐标便捷
    newcenter.x = MAX(halfx, newcenter.x);
    
    //y坐标同理
    float halfy = CGRectGetMidY(self.bounds);
    newcenter.y = MAX(halfy, newcenter.y);
    newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y);
    
    //移动view
    self.center = newcenter;
    
}

@end
